<?php
// +----------------------------------------------------------------------
// | zhanshop-php / UserAuth.php    [ 2025/1/13 11:50 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2025 zhangqiquan All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhangqiquan <768617998@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\middleware;

use app\constant\ApiCode;
use zhanshop\App;
use zhanshop\server\Request;

class UserAuth
{
    public function handle(Request $request, \Closure $next){
        $token = $request->header('token');
        if($token == false || strlen($token) <= 4) App::error()->setError('用户token缺失', ApiCode::TOKEN_MISSING);

        $userId = self::getUserId($token);
        $request->setData('user.user_id', intval($userId));
        return $next($request);
    }

    /**
     * 根据token获取用户ID
     * @param string $token
     * @return void
     * @throws \Exception
     */
    public static function getUserId(string $token)
    {
        try {
            list($userId) = implode(',', App::aes()->decrypt($token));
            return $userId;
        }catch (\Throwable $exception){
            App::error()->setError('用户token无效', ApiCode::TOKEN_ILLEGAL);
        }
    }
}